package com.yeebo.domain.user;

import com.yeebo.dao.user.UserTokenDao;
import com.yeebo.enums.ResultCode;
import com.yeebo.exception.ServiceException;
import com.yeebo.model.user.UserToken;
import com.yeebo.utils.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component("userTokenDomain")
public class UserTokenDomain {

    @Resource
    private UserTokenDao userTokenDao;

    public UserToken getUserTokenByUserInfo(Integer userPlatform, Long userId) {
        UserToken existToken = userTokenDao.getTokenByUserInfo(userPlatform, userId);
        if (existToken == null) {
            existToken = new UserToken();
            Date now = new Date();
            existToken.setUserPlatform(userPlatform);
            existToken.setUserId(userId);
            existToken.setUserToken(IdUtils.generateUserToken(userId));
            existToken.setExpireTime(DateUtils.addDays(now, 7));
            existToken.setCreatedTime(now);
            existToken.setUpdatedTime(now);

            userTokenDao.add(existToken);
        } else {
            refreshUserToken(existToken);
        }
        return existToken;
    }

    public UserToken checkUserTokenValid(Integer userPlatform, String userToken) {
        if (StringUtils.isBlank(userToken)) {
            throw new ServiceException(ResultCode.NEED_LOGIN);
        }
        UserToken existToken = userTokenDao.selectByTokenInfo(userPlatform, userToken);
        if(existToken == null || existToken.getExpireTime().compareTo(new Date()) <= 0) {
            throw new ServiceException(ResultCode.NEED_LOGIN);
        }
        return existToken;
    }

    public void refreshUserToken(UserToken existToken) {
        existToken.setUserToken(IdUtils.generateUserToken(existToken.getUserId()));
        existToken.setExpireTime(DateUtils.addDays(new Date(), 7));
        existToken.setUpdatedTime(new Date());
        userTokenDao.update(existToken);
    }

}
